layui.config({
    base: '../js/layui/lay/modules/' //此处路径请自行处理, 可以使用绝对路径
}).extend({
    formSelects: 'formSelects-v4'
});
layui.use(['form','formSelects','upload'], function () {

    var $ = layui.$, form = layui.form, formSelects = layui.formSelects, upload=layui.upload;
    
    
    $(function () {
        LoginStatus();
        loadCompany();
    })

    //加载城市
    function loadCity(selectId) {
        //formSelect(selectId, formSelects,'expectCity','get','/prop/city/list?page=0&limit=2000','cityname',false);
        //tip(formSelects,'expectCity')

        // $.ajax({
        //     type: 'get', // 提交方式 get/post
        //     url: companyServices+"/prop/city/tree", // 需要提交的 url
        //     contentType:"application/json;charset=utf-8",
        //     xhrFields: {
        //         withCredentials: true
        //     }
        //     ,crossDomain: true
        //     ,data:{},
        //     success: function(res) {
        //         checkLoginStatus(res);
        //         formSelects.data('expectCity', 'local', {
        //             arr:JSON.parse(res).data
        //         });

        //         if (selectId != null) {
        //             formSelects.value('expectCity', selectId.split(','));
        //         }
        //     }
        // })
        layui.use(['treeSelect','form'], function () {
            var treeSelect= layui.treeSelect;
    
            treeSelect.render({
                // 选择器
                elem: '#expectCity',
                // 数据
                data: companyServices+"/prop/city/tree",
                // 异步加载方式：get/post，默认get
                type: 'get',
                // 占位符
                placeholder: '请选择城市',
                // 是否开启搜索功能：true/false，默认false
                search: false,
                // 点击回调
                click: function(d){
                    $("input[name='city']").val(d.current.value)
                },
                // 加载完成后的回调函数
                success: function (d) {
                    // 选中节点，根据id筛选
                    if (selectId) {
                        treeSelect.checkNode('tree', selectId);
                        $("input[name='city']").val(selectId)
                    }
                }
            });
        });
    }


    //加载城市
    function loadIndustry(selectId) {
        //期望行业
        btns(formSelects,'expectIndustry')
        var IndustryArray = arrayAjax('/prop/industry/list?page=0&limit=200','get')
        formSelect(selectId, formSelects,'expectIndustry','get','/prop/industry/list?page=0&limit=200','industryName',true,'/prop/industry',IndustryArray);
        tip(formSelects,'expectIndustry')


        /*$.ajax({
            type: 'get', // 提交方式 get/post
            url: companyServices+"/prop/industry/tree", // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:{},
            success: function(res) {
                formSelects.data('expectIndustry', 'local', {
                    arr:JSON.parse(res).data
                });

                if (selectId != null) {
                    formSelects.value('expectIndustry', selectId.split(','));
                }
            }
        })*/
    }


    //加载公司信息
    function loadCompany() {
        $.ajax({
            type: 'get', // 提交方式 get/post
            url: companyServices+"/company", // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:{},
            success: function(res) {
                checkLoginStatus(res);

                if(res.status == '00200'){
                    var companyInfo = res.data;

                    $('#imageUrlUpload').attr('src', companyServices + companyInfo.logo);
                    $('#fullName').val(companyInfo.fullName);
                    $('#simpleName').val(companyInfo.simpleName);
                    $('#id').val(companyInfo.id);
                    $('#address').val(companyInfo.address);
                    $('#webSite').val(companyInfo.webSite);
                    $('#description').val(companyInfo.description);

                    //加载公司等级
                    loadSelectData('companySizeLevelSelect', companyInfo.companySizeLevel , '/prop/companyLevel/list?page=1&limit=200');
                    //加载公司类型
                    loadSelectData('companyTypeSelect', companyInfo.companyTypeId, '/company/type?page=1&limit=200');
                    loadCity(companyInfo.city);
                    loadIndustry(companyInfo.industryId);
                }
            }
        })
    }

    //普通图片上传
    upload.render({
        elem: '#imageUrlUpload'
        , url: companyServices+"/user/upload/img"
        , before: function (obj) {
            //预读本地文件示例，不支持ie8

        }
        , done: function (res) {
            if(res.code==0){
                var fullPath = companyServices + res.data.src;
                $('#imageUrlUpload').attr('src',fullPath);
                $('#img').val(res.data.src) ;
                layer.msg(res.msg);
            }
        }
        , error: function () {
            layer.msg("上传失败");
        }
    });

    form.on('submit(btnSave)', function (data) {

        data.field.industryId = formSelects.value('expectIndustry', 'valStr');
        // data.field.city = formSelects.value('expectCity', 'valStr');

        layer.load(2);
        $.ajax({
            type: 'post', // 提交方式 get/post
            url: companyServices+"/company", // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:JSON.stringify(data.field),
            success: function(res) {
                layer.closeAll('loading');
                if(res.status == '00200'){
                    layerMsg(res.message);
                    setTimeout(function() {
                        window.location.href="wrap-company-set.html" ;
                    }, 2000);

                }else{
                    layerMsg(res.message)
                }
            },fail:function () {
                layer.closeAll('loading');
            }
        })
        return false;
    });



    //加载下拉选项并选中，如果selectId存在并且相等
    function loadSelectData(selectName, selectId, url) {
        var html = '<option value="">请选择</option>';

        $.ajax({
            type: 'get', // 提交方式 get/post
            url: companyServices+url, // 需要提交的 url
            contentType:"application/json;charset=utf-8",
            xhrFields: {
                withCredentials: true
            }
            ,crossDomain: true
            ,data:{},
            success: function(res) {
                if (JSON.parse(res).data != null) {

                    $.each(JSON.parse(res).data, function (index, item) {
                        if (selectId != null && selectId != '' && selectId == item.id) {
                            html += '<option value="'+item.id+'" selected>'+item.name+'</option>';
                        } else {
                            html += '<option value="'+item.id+'">'+item.name+'</option>';
                        }
                    })

                    $('#' + selectName).html(html);
                    form.render();

                }
            }
        })
    }


    function formSelect(selectId,formSelects,_id,_type,_url,_name,Insert=true,Inserturl="",array=[]){
        formSelects.config(_id, {
            type: _type,                //请求方式: post, get, put, delete...
            searchName: _name,      //自定义搜索内容的key值
            searchVal: '',              //自定义搜索内容, 搜素一次后失效, 优先级高于搜索框中的值
            keyName: _name,            //自定义返回数据中name的key, 默认 name
            searchUrl: companyServices+_url,
            keyVal: 'id',            //自定义返回数据中value的key, 默认 value
            delay: 500,  //搜索延迟时间, 默认停止输入500ms后开始搜索\
            response: {
                statusCode: 0,          //成功状态码
                statusName: 'code',     //code key
                msgName: 'msg',         //msg key
                dataName: 'data'  ,      //data key
            },
            beforeSuccess: function(id, url, searchVal,result){
                if(result.code==0){
                    if(result.count==0){
                        result.code = 201;
                        result.msg = "没有找到选项";
                        if(Insert){
                            btns(formSelects,id,_url,array,searchVal,Inserturl,'put',_name);
                        }
                    }
                }
                return result;  //必须return一个结果, 这个结果要符合对应的数据结构
            },
            error: function(id, url, searchVal, err){           //使用远程方式的error回调
                //同上
                console.log(err);   //err对象
            },
            success:function () {
                if (selectId != null) {
                    if (_id == 'expectCity') {
                        formSelects.value(_id, selectId.toString().split(','));
                    } else {
                        formSelects.value(_id, selectId.split(","));
                    }

                }
            }
        }, false)
    }

    function InsertApi(_addurl,_addtype,_name,_value){
        var arrdata = {};
        arrdata[_name] = _value;
        arrdata["pid"] = '0';
        var result = ""
        $.ajax({
            type: _addtype, // 提交方式 get/post
            url:companyServices+_addurl,
            contentType:"application/json;charset=utf-8",
            async:false,
            // contentType:"application/json;charset=utf-8",
            //解决跨域
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            data:JSON.stringify(arrdata),
            success: function(res) {
                result = JSON.stringify(res);
                ApiLoginStatus(result)
                if(res.success){
                    result = res;
                }
            },
        });
        return result;

    }

    function localAPi(formSelects,_id,searchVal,key,value,timestamp,array){

        var arr = {};
        arr[key]=timestamp;
        arr[value]=searchVal;
        array.push(arr)
        //local模式
        formSelects.data(_id, 'local', {
            arr:array
        });
        return array;
    }

    function serviceAPI(formSelects,_id,_url){
        formSelects.data(_id, 'server', {
            url:companyServices+_url
        });
    }

    function btns(formSelects,_id,_url,array,_value="",_addurl="",_addtype="",_name=""){
        formSelects.btns(_id, ['select', 'remove', {
            icon: 'layui-icon layui-icon-ok',   //自定义图标, 可以使用layui内置图标
            name: '添加',
            click: function(id){
                if(_value){
                    var res = InsertApi(_addurl,_addtype,_name,_value)
                    if(res.success){
                        idvalue = res.data.id;
                        localAPi(formSelects,_id,_value,'id',_name,idvalue,array)
                    }
                }
            }
        }]);

    }
    function search(formSelects,_id,keyword){
        //使用js主动触发搜索
        formSelects.search(_id, keyword);
    }

    function arrayAjax(_url,_type){
        var array = [];
        $.ajax({
            type: _type, // 提交方式 get/post
            url:companyServices+_url,
            async:false,
            // contentType:"application/json;charset=utf-8",
            //解决跨域
            xhrFields: {
                withCredentials: true
            },
            crossDomain: true,
            success: function(res) {
                var obj = JSON.parse(res)
                if(obj.code==0){
                    array = obj.data;
                }
            }
        })
        return array;
    }


    function tip(formSelects,selectID){
        formSelects.maxTips(selectID, function(id, vals, val, max){
            //id:   点击select的id
            //vals: 当前select已选中的值
            //val:  当前select点击的值
            //max:  当天多选最大值
            layerMsg("最多只能选择"+max+"个选项")
        });
    }

});